package br.com.ledger.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.AbstractListModel;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;

import br.com.ledger.controll.Banco;
import br.com.ledger.controll.ModeloDados;
import br.com.ledger.model.BalanceteVerificacaoBean;
import br.com.ledger.model.IModel;
import br.com.ledger.model.RazoneteBean;
import br.com.ledger.utils.JTextFieldLimit;
import br.com.ultimate.components.InfoPane;

@SuppressWarnings("serial")
public class TelaRazonetes extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField txtBalancete;
	private JList lstBalancete;
	private ArrayList<IModel> balancetes;
	private JRadioButton rdBalancetes, rdNovo;
	
	/**
	 * Balancete
	 */
	private BalanceteVerificacaoBean balancete;
	
	private final ButtonGroup buttonGroup = new ButtonGroup();

	/**
	 * Create the dialog.
	 */
	public TelaRazonetes() {
		balancetes = new ArrayList<IModel>();
		init();
	}
	
	/**
	 * 
	 */
	private void init() {
		
		setResizable(false);
		setModal(true);
		setTitle("Razonetes");
		setSize(516, 382);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBackground(new Color(244, 244, 244));
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(8, 121, 484, 113);
		contentPanel.add(scrollPane);
		
		lstBalancete = new JList();
		lstBalancete.setBorder(new EmptyBorder(10, 10, 10, 10));
		lstBalancete.setBackground(new Color(250, 250, 250));
		lstBalancete.setEnabled(false);
		scrollPane.setViewportView(lstBalancete);
		
		rdNovo = new JRadioButton("Criar um novo Plano de Razonetes com nome:");
		rdNovo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				txtBalancete.setEnabled(true);
				lstBalancete.setEnabled(false);
				txtBalancete.requestFocus();
			}
		});
		rdNovo.setOpaque(false);
		rdNovo.setSelected(true);
		rdNovo.setBounds(8, 8, 486, 24);
		contentPanel.add(rdNovo);
		
		txtBalancete = new JTextField();
		txtBalancete.setDocument(new JTextFieldLimit(50));
		txtBalancete.setBounds(10, 40, 216, 24);
		contentPanel.add(txtBalancete);
		txtBalancete.setColumns(10);
		
		rdBalancetes = new JRadioButton("Selecionar um balancete existente para gerar os razonetes:");
		rdBalancetes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				txtBalancete.setEnabled(false);
				lstBalancete.setEnabled(true);
				lstBalancete.requestFocus();
			}
		});
		rdBalancetes.setOpaque(false);
		rdBalancetes.setBounds(8, 89, 484, 24);
		contentPanel.add(rdBalancetes);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setBorder(new MatteBorder(1, 0, 0, 0, (Color) new Color(169, 169, 169)));
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if (rdNovo.isSelected())
							criar();
						else if (rdBalancetes.isSelected())
							abrir();
					}
				});
				okButton.setBackground(new Color(220, 220, 220));
				okButton.setPreferredSize(new Dimension(80, 40));
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancelar");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						TelaRazonetes.this.balancetes = null;
						dispose();
					}
				});
				cancelButton.setBackground(new Color(220, 220, 220));
				cancelButton.setPreferredSize(new Dimension(80, 40));
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
		
		buttonGroup.add(rdNovo);
		buttonGroup.add(rdBalancetes);
		
		InfoPane infoPane = new InfoPane();
		infoPane.setBackground(new Color(230, 230, 250));
		infoPane.setIcon(Toolkit.getDefaultToolkit().getImage(TelaRazonetes.class.getResource("/res/menu_list.png")));
		infoPane.setText("<html><div style='margin-left:5px;'>Crie um novo plano de razonetes ou selecione um balancete de verfica\u00E7\u00E3o<br>j\u00E1 existente para gerar o plano de razonetes.</div></html>");
		getContentPane().add(infoPane, BorderLayout.NORTH);
		
		// -------------------
		setLocationRelativeTo(TelaInicial.getInstance());
		consultarBalancetes();
		atualizarLista();
		txtBalancete.requestFocus();
		setVisible(true);
	}
	
	/**
	 * 
	 */
	private void atualizarLista() {
		
		lstBalancete.setModel(new AbstractListModel() {
			String[] values = new String[balancetes.size()];
			{
				for (int i = 0; i < balancetes.size(); i++) 
					values[i] = ((BalanceteVerificacaoBean) balancetes.get(i)).getNome();
			}
			public int getSize() {
				return values.length;
			}
			public Object getElementAt(int index) {
				return values[index];
			}
		});
	}
	
	
	/**
	 * 
	 */
	private void consultarBalancetes() {
		balancetes = Banco.getInstance().consultar(BalanceteVerificacaoBean.class,
				ModeloDados.BalanceteVerificao.projeto, Main.Ledger.getProjeto().getCodigo(), "=");
	}
	
	
	/**
	 * 
	 */
	private void criar() {
		if (!txtBalancete.getText().equals("")) {
			Banco.getInstance().adicionar(new BalanceteVerificacaoBean(-1, Main.Ledger.getUsuario(), Main.Ledger.getProjeto(), txtBalancete.getText(), 0, 0));
			this.balancete = (BalanceteVerificacaoBean) Banco.getInstance().consultar(BalanceteVerificacaoBean.class, ModeloDados.BalanceteVerificao.codigo,
					Banco.getInstance().getOperacoes().getMaxID(ModeloDados.BalanceteVerificao.codigo, "balancete_verificacao"), "=").get(0);
			dispose();
		}
	}
	
	
	/**
	 * 
	 */
	private void abrir() {
		this.balancete = (BalanceteVerificacaoBean) balancetes.get(lstBalancete.getSelectedIndex());
		ArrayList<IModel> registros = Banco.getInstance().consultar(RazoneteBean.class, ModeloDados.Razonete.balancete, balancete.getCodigo(), "=");
		
		for (IModel r : registros) {
			balancete.addRegistro((RazoneteBean) r);
		}
		
		dispose();
	}
	
	/**
	 * 
	 */
	public BalanceteVerificacaoBean getBalanceteVerificacao() {
		return this.balancete;
	}
}
